#!/bin/sh
# Reversible OpenWrt IPv6 leak guard. The Rust caller supplies a 30s outer
# deadline; package installers also invoke this through their bounded runner.
STATE_DIR="${RELAYWAY_IPV6_GUARD_STATE_DIR:-/etc/relayway/ipv6-leak-guard}"
INIT_DIR="${RELAYWAY_IPV6_GUARD_INIT_DIR:-/etc/init.d}"
LOGTAG=relayway-ipv6-guard

log() { logger -t "$LOGTAG" "$*" 2>/dev/null || true; }
fail() { log "ERROR: $*"; return 1; }
opt() { uci -q get "relayway.cored.$1" 2>/dev/null || true; }
enabled() {
    local value
    value="$(opt ipv6_leak_guard)"; [ -n "$value" ] || value=1
    case "$value" in 0|false|FALSE|off|OFF|no|NO|disabled|DISABLED) return 1 ;; esac
}
lan_section() { local value; value="$(opt ipv6_leak_guard_lan)"; printf '%s\n' "${value:-lan}"; }
# Emit every UCI LAN member whose NAME we can safely put in an argv, whether or
# not the device is up right now.
#
# Aborting on the first unusable one meant a USB tether or a not-yet-up VLAN in
# the UCI list blocked TUN activation for the entire router. But *skipping* a
# configured-but-down member is a hotplug leak: nft `iifname` and ip6tables `-i`
# both accept a name that does not currently resolve, and the rule starts
# matching the moment the device appears -- so omitting it means clients on that
# interface get native WAN IPv6 as soon as it comes up, with the TUN still
# active. Install for it now; that also keeps removal symmetric, since
# remove_forward_guard re-enumerates this same list.
#
# A name we cannot put in an argv is a different case: it is skipped, and the
# empty-list refusal below still covers "nothing usable left".
lan_ifaces() {
    local names name found
    names="$(uci -q get network.lan.device 2>/dev/null || true)"
    [ -n "$names" ] || names="$(uci -q get network.lan.ifname 2>/dev/null || true)"
    [ -n "$names" ] || names=br-lan
    found=0
    for name in $names; do
        case "$name" in ''|*[!A-Za-z0-9_.:-]*) log "skipping unsafe LAN name: $name"; continue ;; esac
        [ "${#name}" -le 15 ] || { log "skipping over-long LAN name: $name"; continue; }
        ip link show dev "$name" >/dev/null 2>&1 \
            || log "LAN device is not present yet; guarding it anyway for hotplug: $name"
        found=1
        printf '%s\n' "$name"
    done
    [ "$found" = 1 ]
}
# A router without odhcpd has no daemon to restart, and dhcp.<lan>.ra/dhcpv6/ndp
# are odhcpd's options -- with it absent they are inert, so nothing is serving RA
# from them and the FORWARD reject is what actually contains IPv6. Treating that
# as a failure refused TUN activation outright on such images. A restart that IS
# attempted and fails is still a failure.
restart_odhcpd() {
    if [ ! -x "$INIT_DIR/odhcpd" ]; then
        log "odhcpd init script absent; RA/DHCPv6/NDP options are inert here"
        return 0
    fi
    "$INIT_DIR/odhcpd" restart >/dev/null 2>&1
}
write_snapshot() {
    local section="$1" parent tmp key value
    [ ! -e "$STATE_DIR" ] || { [ -d "$STATE_DIR" ] && return 0; return 1; }
    parent="${STATE_DIR%/*}"; [ "$parent" != "$STATE_DIR" ] || parent=.
    mkdir -p "$parent" || return 1
    tmp="$STATE_DIR.new.$$"; (umask 077; mkdir "$tmp") || return 1
    (umask 077; printf '%s\n' "$section" > "$tmp/section") || { rm -rf "$tmp"; return 1; }
    for key in ra dhcpv6 ndp; do
        if value="$(uci -q get "dhcp.$section.$key" 2>/dev/null)"; then
            [ -n "$value" ] || value=__empty__
        else
            value=__unset__
        fi
        (umask 077; printf '%s\n' "$value" > "$tmp/$key") || { rm -rf "$tmp"; return 1; }
    done
    mv "$tmp" "$STATE_DIR" || { rm -rf "$tmp"; return 1; }
}
valid_snapshot() {
    local key
    [ -d "$STATE_DIR" ] && [ -s "$STATE_DIR/section" ] || return 1
    for key in ra dhcpv6 ndp; do [ -s "$STATE_DIR/$key" ] || return 1; done
}

remove_forward_guard() {
    local iface
    if command -v nft >/dev/null 2>&1; then
        nft delete table inet relayway_ipv6_guard >/dev/null 2>&1 || true
        nft list table inet relayway_ipv6_guard >/dev/null 2>&1 && return 1
    fi
    if command -v ip6tables >/dev/null 2>&1; then
        for iface in $(lan_ifaces 2>/dev/null || true); do
            while ip6tables -D FORWARD -i "$iface" -m comment \
                --comment relayway-ipv6-guard -j REJECT >/dev/null 2>&1; do :; done
        done
    fi
}
install_nft_forward_guard() {
    local iface
    command -v nft >/dev/null 2>&1 || return 1
    nft add table inet relayway_ipv6_guard >/dev/null 2>&1 || return 1
    nft 'add chain inet relayway_ipv6_guard forward { type filter hook forward priority -10; policy accept; }' >/dev/null 2>&1 || return 1
    for iface in $1; do
        nft add rule inet relayway_ipv6_guard forward iifname "$iface" meta nfproto ipv6 \
            counter reject comment relayway-ipv6-guard >/dev/null 2>&1 || return 1
    done
    nft list table inet relayway_ipv6_guard >/dev/null 2>&1
}
install_ip6tables_forward_guard() {
    local iface
    command -v ip6tables >/dev/null 2>&1 || return 1
    for iface in $1; do
        ip6tables -I FORWARD 1 -i "$iface" -m comment \
            --comment relayway-ipv6-guard -j REJECT >/dev/null 2>&1 || return 1
        ip6tables -C FORWARD -i "$iface" -m comment \
            --comment relayway-ipv6-guard -j REJECT >/dev/null 2>&1 || return 1
    done
}
# Committing to nft on `command -v nft` alone and then returning on the first nft
# failure made the ip6tables branch unreachable on a box with nft userspace but no
# nft kernel modules -- the same "backend picked by binary presence, never
# revisited on failure" shape as the fw4 probe in openwrt_policy.rs. Fall through.
# The kernel creates /proc/net/if_inet6 if and only if IPv6 support is compiled
# in, so its ABSENCE is positive proof that this box cannot carry an IPv6 packet
# at all -- not merely that we failed to find a tool to block one with.
# Overridable only so the test suite can assert BOTH branches deterministically:
# it runs off-router, where the real path never exists, so without this the tests
# would be asserting the host kernel's configuration instead of this script's.
kernel_has_ipv6() {
    [ -e "${RELAYWAY_IPV6_GUARD_IF_INET6:-/proc/net/if_inet6}" ]
}
install_forward_guard() {
    local ifaces
    ifaces="$(lan_ifaces)" || return 1
    remove_forward_guard || return 1
    install_nft_forward_guard "$ifaces" && return 0
    log "nft IPv6 forward guard unavailable; falling back to ip6tables"
    remove_forward_guard || true
    install_ip6tables_forward_guard "$ifaces" && return 0
    # Both backends failed. On a CONFIG_IPV6=n image -- a legitimate custom fw3
    # build with IPv4 iptables and neither nft nor ip6tables -- there is no IPv6
    # stack to leak through, so refusing every activation only cost the operator
    # their connection until they turned the guard off by hand.
    #
    # This is allowed ONLY on that positive proof. A missing tool is not evidence
    # that IPv6 is absent: a box WITH an IPv6 stack and no way to block it is
    # exactly the leak this guard exists to prevent, and still refuses.
    if kernel_has_ipv6; then
        return 1
    fi
    log "no IPv6 forward guard installed: this kernel has no IPv6 stack (/proc/net/if_inet6 absent), so there is nothing to leak"
    return 0
}
restore_value() {
    local section="$1" key="$2" value
    value="$(cat "$STATE_DIR/$key" 2>/dev/null)" || return 1
    case "$value" in
        __unset__) uci -q delete "dhcp.$section.$key" 2>/dev/null || true ;;
        __empty__) uci -q set "dhcp.$section.$key=" 2>/dev/null || return 1 ;;
        *) uci -q set "dhcp.$section.$key=$value" 2>/dev/null || return 1 ;;
    esac
}
restore_guard() {
    local section
    remove_forward_guard || return 1
    [ ! -e "$STATE_DIR" ] && return 0
    command -v uci >/dev/null 2>&1 || return 1
    valid_snapshot || return 1
    section="$(cat "$STATE_DIR/section" 2>/dev/null)" || return 1
    uci -q show "dhcp.$section" >/dev/null 2>&1 || return 1
    restore_value "$section" ra || return 1
    restore_value "$section" dhcpv6 || return 1
    restore_value "$section" ndp || return 1
    uci -q commit dhcp >/dev/null 2>&1 || return 1
    restart_odhcpd || return 1
    rm -rf "$STATE_DIR" || return 1
    log "restored LAN IPv6 forwarding and dhcp.$section RA/DHCPv6/NDP"
}
apply_guard() {
    local section
    enabled || { log "IPv6 leak guard explicitly disabled"; return 0; }
    # Without uci we cannot snapshot or disable RA/DHCPv6/NDP -- but the FORWARD
    # reject IS the leak barrier and it needs no uci. `return 0` here used to skip
    # the guard ENTIRELY and report success, so activation proceeded with LAN IPv6
    # wide open, while a merely-missing dhcp section two lines later refused. That
    # was backwards. Install what we can, and fail if even that fails.
    if ! command -v uci >/dev/null 2>&1; then
        log "uci unavailable; installing the IPv6 FORWARD guard without the RA/DHCPv6/NDP snapshot"
        install_forward_guard || { remove_forward_guard || true; return 1; }
        return 0
    fi
    section="$(lan_section)"
    # Overridable via `uci set relayway.cored.ipv6_leak_guard_lan` for bridge-only,
    # multi-LAN and renamed-section firmwares. Say so: this was a silent `return 1`
    # and the operator saw only the caller's generic "apply OpenWrt IPv6 leak guard".
    # Same reasoning as the missing-uci branch above, which this used to
    # contradict: a missing dhcp section means there is no RA/DHCPv6/NDP state to
    # snapshot, NOT that the leak barrier cannot be installed. Refusing here
    # failed every connect on a minimal or IPv4-only OpenWrt that simply has no
    # `config dhcp 'lan'` and no odhcpd -- a router with nothing to leak.
    #
    # It is equally safe when the cause is a renamed or multi-LAN section: the
    # FORWARD reject blocks forwarded IPv6 whatever odhcpd hands out, so clients
    # may hold an address but cannot route through us. The operator still needs
    # to know, because leaving RA on is not the intended posture.
    uci -q show "dhcp.$section" >/dev/null 2>&1 || {
        log "no dhcp.$section section; installing the IPv6 FORWARD guard without the \
RA/DHCPv6/NDP snapshot -- if this router does serve IPv6, set \
relayway.cored.ipv6_leak_guard_lan to the right section"
        install_forward_guard || { remove_forward_guard || true; return 1; }
        return 0
    }
    write_snapshot "$section" || return 1
    install_forward_guard || { restore_guard; return 1; }
    uci -q set "dhcp.$section.ra=disabled" >/dev/null 2>&1 || { restore_guard; return 1; }
    uci -q set "dhcp.$section.dhcpv6=disabled" >/dev/null 2>&1 || { restore_guard; return 1; }
    uci -q set "dhcp.$section.ndp=disabled" >/dev/null 2>&1 || { restore_guard; return 1; }
    uci -q commit dhcp >/dev/null 2>&1 || { restore_guard; return 1; }
    restart_odhcpd || { restore_guard; return 1; }
    log "blocked LAN IPv6 forwarding and disabled dhcp.$section RA/DHCPv6/NDP"
}

case "$1" in
    apply) apply_guard ;;
    restore) restore_guard ;;
    *) echo "Usage: $0 {apply|restore}" >&2; exit 2 ;;
esac
